package com.lxmes.business.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.lxmes.base.domain.JcIteminfo;
import com.lxmes.base.domain.JcIteminfoDistri;
import com.lxmes.base.domain.JcWarehouseinfoKuwei;
import com.lxmes.base.mapper.JcIteminfoMapper;
import com.lxmes.base.mapper.JcWarehouseinfoKuweiMapper;
import com.lxmes.base.service.impl.JcIteminfoDistriServiceImpl;
import com.lxmes.business.domain.*;
import com.lxmes.business.mapper.*;
import com.lxmes.common.exception.ServiceException;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.NewNumber;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.business.service.ICcRukuInfoService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;

/**
 * 入库单Service业务层处理
 *
 * @author 张志煜
 * @date 2022-11-27
 */
@Service
public class CcRukuInfoServiceImpl implements ICcRukuInfoService
{
    private static final Logger log = LoggerFactory.getLogger(JcIteminfoDistriServiceImpl.class);

    @Autowired
    private CcRukuInfoMapper ccRukuInfoMapper;
    @Autowired
    private JcIteminfoMapper jcIteminfoMapper;
    @Autowired
    private CcStockInfoMapper stockInfoMapper;
    @Autowired
    private JcWarehouseinfoKuweiMapper kuweiMapper;
    @Autowired
    private CcPurchaseInfoMapper ccPurchaseInfoMapper;
    @Autowired
    private CcPurchaseInfoSpMapper ccPurchaseInfoSpMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private CcChukuInfoMapper chukuInfoMapper;

    /**
     * 查询入库单
     *
     * @param id 入库单主键
     * @return 入库单
     */
    @Override
    public CcRukuInfo selectCcRukuInfoById(Long id)
    {
        return ccRukuInfoMapper.selectCcRukuInfoById(id);
    }

    /**
     * 查询入库单列表
     *
     * @param ccRukuInfo 入库单
     * @return 入库单
     */
    @Override
    public List<CcRukuInfo> selectCcRukuInfoList(CcRukuInfo ccRukuInfo)
    {
        ccRukuInfo.setFactoryCode(SecurityUtils.getFactoryCode());
        return ccRukuInfoMapper.selectCcRukuInfoList(ccRukuInfo);
    }

    @Override
    public List<CcRukuInfo> selectCcRukuInfoMainList(CcRukuInfo ccRukuInfo) {
        ccRukuInfo.setFactoryCode(SecurityUtils.getFactoryCode());
        return ccRukuInfoMapper.selectCcRukuInfoMainList(ccRukuInfo);
    }

    @Override
    public List<CcRukuInfo> selectJieSuanCcRukuInfoList(CcRukuInfo ccRukuInfo) {
        ccRukuInfo.setFactoryCode(SecurityUtils.getFactoryCode());
        return ccRukuInfoMapper.selectJieSuanCcRukuInfoList(ccRukuInfo);
    }

    /**
     * 新增入库单
     *
     * @param ccRukuInfo 入库单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCcRukuInfo(CcRukuInfo ccRukuInfo)
    {
        String number= "RK-"+ NewNumber.createNewNumber(ccRukuInfoMapper.getNewCode(DateUtils.getDate()));
        List<CcRukuInfo> list = ccRukuInfo.getInfoList();
        if(list.size()>0){
            for ( CcRukuInfo info:list) {
                String[] kuweiArr = info.getWarehouse();
                JcWarehouseinfoKuwei kuwei = kuweiMapper.selectJcWarehouseinfoKuweiByKuweiJmCode(kuweiArr[2]);
                if(kuwei==null){
                    throw new ServiceException("未找到库位信息！");
                }
                info.setKuquCode(kuwei.getKuquCode());
                info.setItemCode(info.getItemCode());
                info.setItemId(info.getItemId());
                info.setKuquName(kuwei.getKuquName());
                info.setKuweiCode(kuwei.getKuweiJmCode());
                info.setStockId(kuwei.getStockCode());
                info.setStockName(kuwei.getStockName());
                info.setDanhao(number);
                info.setRukuDate(ccRukuInfo.getRukuDate());
                info.setOrderType(ccRukuInfo.getOrderType());
                info.setClientName(ccRukuInfo.getClientName());
                info.setClientCode(ccRukuInfo.getClientCode());
                info.setCreateTime(DateUtils.getNowDate());
                info.setCreateBy(SecurityUtils.getUsername());
                info.setFactoryName(SecurityUtils.getFactoryName());
                info.setFactoryCode(SecurityUtils.getFactoryCode());
                info.setSupplyName(ccRukuInfo.getSupplyName());
                info.setSupplyId(ccRukuInfo.getSupplyId());
                info.setLot(DateUtils.dateTime());
                info.setOrderType(ccRukuInfo.getOrderType());
                info.setRukuType(ccRukuInfo.getRukuType());
                info.setQualityState("1");
                info.setOrderDanhao(ccRukuInfo.getOrderDanhao());
                info.setPlanId(ccRukuInfo.getPlanId());
                info.setContractCode(ccRukuInfo.getContractCode());
                info.setState(1L);
                ccRukuInfoMapper.insertCcRukuInfo(info);
                //同步库存
                this.saveStock(info);
            }
        }else {
            throw new ServiceException("物料不存在！");
        }
        return 1;
    }

    //流转入库
    @Override
    public int insertCkCcRukuInfo(CcRukuInfo ccRukuInfo) {
        String number= "RK-"+ NewNumber.createNewNumber(ccRukuInfoMapper.getNewCode(DateUtils.getDate()));
        List<CcRukuInfo> list = ccRukuInfo.getInfoList();
        if(list.size()>0){
            for ( CcRukuInfo info:list) {
                String[] kuweiArr = info.getWarehouse();
                JcWarehouseinfoKuwei kuwei = kuweiMapper.selectJcWarehouseinfoKuweiByKuweiJmCode(kuweiArr[2]);
                if(kuwei==null){
                    throw new ServiceException("未找到库位信息！");
                }
                info.setKuquCode(kuwei.getKuquCode());
                info.setItemCode(info.getItemCode());
                info.setItemId(info.getItemId());
                info.setKuquName(kuwei.getKuquName());
                info.setKuweiCode(kuwei.getKuweiJmCode());
                info.setStockId(kuwei.getStockCode());
                info.setStockName(kuwei.getStockName());
                info.setDanhao(number);
                info.setRukuDate(ccRukuInfo.getRukuDate());
                info.setOrderType(ccRukuInfo.getOrderType());
                info.setClientName(ccRukuInfo.getClientName());
                info.setClientCode(ccRukuInfo.getClientCode());
                info.setCreateTime(DateUtils.getNowDate());
                info.setCreateBy(SecurityUtils.getUsername());
                info.setFactoryName(SecurityUtils.getFactoryName());
                info.setFactoryCode(SecurityUtils.getFactoryCode());
                info.setLot(DateUtils.dateTime());
                info.setOrderType(ccRukuInfo.getOrderType());
                info.setRukuType(ccRukuInfo.getRukuType());
                info.setQualityState("1");
                info.setOrderDanhao(StringUtils.isNotEmpty(ccRukuInfo.getOrderDanhao())?ccRukuInfo.getOrderDanhao():info.getOrderDanhao());
                info.setPlanId(StringUtils.isNotEmpty(ccRukuInfo.getPlanId())?ccRukuInfo.getPlanId():info.getPlanId());
                info.setContractCode(StringUtils.isNotEmpty(ccRukuInfo.getContractCode())?ccRukuInfo.getContractCode():info.getContractCode());
                //回写出库单
                CcChukuInfo chuku = chukuInfoMapper.selectCcChukuInfoById(info.getCkId());
                if(chuku.getZzrkNum().add(info.getRukuNum()).compareTo(chuku.getCkNum())>0){
                    throw new ServiceException("物料:"+info.getItemId()+"超出流转出库数量");
                }
                chuku.setZzhxState("1");
                chuku.setZzrkName(SecurityUtils.getUsername());
                chuku.setZzrkTime(new Date());
                chuku.setZzrkNum(chuku.getZzrkNum().add(info.getRukuNum()));
                chuku.setZzrkRemark(StringUtils.isBlank(chuku.getRemark())?info.getKuweiCode():"、"+info.getKuweiCode());
                chukuInfoMapper.updateCcChukuInfo(chuku);
                info.setState(1L);
                ccRukuInfoMapper.insertCcRukuInfo(info);
                //同步库存
                this.saveStock(info);
            }
        }else {
            throw new ServiceException("物料不存在！");
        }
        return 1;
    }
    //整单入库
    @Override
    @Transactional
    public int zdRuKu(CcRukuInfo ccRukuInfo) {
        CcChukuInfo chukuInfo=new CcChukuInfo();
        chukuInfo.setDanhao(ccRukuInfo.getDanhao());
        chukuInfo.setCkState(1L);
        List<CcChukuInfo> chukuList = chukuInfoMapper.selectCcChukuInfoList(chukuInfo);
        String number= "RK-"+ NewNumber.createNewNumber(ccRukuInfoMapper.getNewCode(DateUtils.getDate()));
        if(chukuList.size()>0){
            CcRukuInfo rukuInfoQ=new CcRukuInfo();
            rukuInfoQ.setPlanId(ccRukuInfo.getDanhao());
            List<CcRukuInfo> rukuIsCz = ccRukuInfoMapper.selectCcRukuInfoList(rukuInfoQ);
            if(rukuIsCz.size()>0){
                throw new ServiceException("出库单号["+ccRukuInfo.getDanhao()+"]已入库，请勿重复！！！");
            }
        for (CcChukuInfo ccChukuInfo:chukuList) {
            CcRukuInfo rukuInfo=new CcRukuInfo();
               BeanUtils.copyProperties(ccChukuInfo,rukuInfo);
                rukuInfo.setRukuNum(ccChukuInfo.getCkNum());
                rukuInfo.setKuquName(ccRukuInfo.getKuquName());
                rukuInfo.setKuquCode(ccRukuInfo.getKuquCode());
                rukuInfo.setKuweiCode(ccRukuInfo.getKuweiCode());
                rukuInfo.setStockId(ccRukuInfo.getStockId());
                rukuInfo.setStockName(ccRukuInfo.getStockName());
                rukuInfo.setDanhao(number);
                rukuInfo.setPlanId(ccRukuInfo.getDanhao());
                rukuInfo.setRukuDate(ccRukuInfo.getRukuDate());
                rukuInfo.setOrderType(ccRukuInfo.getOrderType());
                rukuInfo.setCreateTime(DateUtils.getNowDate());
                rukuInfo.setCreateBy(SecurityUtils.getUsername());
                rukuInfo.setLot(DateUtils.dateTime());
                rukuInfo.setRukuType(ccRukuInfo.getRukuType());
                rukuInfo.setState(1L);
                ccRukuInfoMapper.insertCcRukuInfo(rukuInfo);
                this.saveStock(rukuInfo);
        }
        }else {
            throw new ServiceException("未查到出库单！！！");
        }
        return 1;
    }
    //手机端扫码入库
    @Override
    @Transactional
    public int insertSmCcRukuInfo(CcRukuInfo rukuInfo) {
        String number= "RK-"+ NewNumber.createNewNumber(ccRukuInfoMapper.getNewCode(DateUtils.getDate()));
        rukuInfo.setFactoryName(SecurityUtils.getFactoryName());
        rukuInfo.setFactoryCode(SecurityUtils.getFactoryCode());
        rukuInfo.setDanhao(number);
        rukuInfo.setCreateTime(DateUtils.getNowDate());
        rukuInfo.setCreateBy(SecurityUtils.getUsername());
        rukuInfo.setLot(DateUtils.dateTime());
        rukuInfo.setQualityState("1");
        rukuInfo.setTotalPrice(rukuInfo.getRukuNum().multiply(rukuInfo.getUnitPrice()));
        //下面不执行直接入库，同步库存
        rukuInfo.setState(1L);
        this.saveStock(rukuInfo);
        ccRukuInfoMapper.insertCcRukuInfo(rukuInfo);
        return 1;
    }
    //订单入库
    @Override
    @Transactional
    public int insertPurCcRukuInfo(CcRukuInfo ccRukuInfo) {
        //计入库存id
        List<Long> ids = new ArrayList<>();
        String number= "RK-"+ NewNumber.createNewNumber(ccRukuInfoMapper.getNewCode(DateUtils.getDate()));
        List<CcRukuInfo> list = ccRukuInfo.getInfoList();
        if(list.size()>0){
            for ( CcRukuInfo info:list) {
                String[] kuweiArr = info.getWarehouse();
                JcWarehouseinfoKuwei kuwei = kuweiMapper.selectJcWarehouseinfoKuweiByKuweiJmCode(kuweiArr[2]);
                if (kuwei == null) {
                    throw new ServiceException("未找到库位信息！");
                }
                if ("1".equals(kuwei.getKuweiType())) {
                    throw new ServiceException("采购订单不支持入中心库位");
                }
                info.setKuquCode(kuwei.getKuquCode());
                info.setItemCode(info.getItemCode());
                info.setItemId(info.getItemId());
                info.setKuquName(kuwei.getKuquName());
                info.setKuweiCode(kuwei.getKuweiJmCode());
                info.setStockId(kuwei.getStockCode());
                info.setStockName(kuwei.getStockName());
                info.setDanhao(number);
                info.setRukuDate(new Date());
                info.setOrderType(ccRukuInfo.getOrderType());
                info.setClientName(ccRukuInfo.getClientName());
                info.setClientCode(ccRukuInfo.getClientCode());
                info.setCreateTime(DateUtils.getNowDate());
                info.setCreateBy(SecurityUtils.getUsername());
                info.setFactoryName(SecurityUtils.getFactoryName());
                info.setFactoryCode(SecurityUtils.getFactoryCode());
                info.setLot(DateUtils.dateTime());
                info.setOrderType(ccRukuInfo.getOrderType());
                info.setRukuType(ccRukuInfo.getRukuType());
                info.setQualityState("1");
                info.setState(1L);
               /* info.setOrderDanhao(ccRukuInfo.getOrderDanhao());
                info.setPlanId(ccRukuInfo.getPlanId());
                info.setContractCode(ccRukuInfo.getContractCode());*/
                ccRukuInfoMapper.insertCcRukuInfo(info);
                this.saveStock(info);
                if (info.getRukuType().longValue() == 0L) {
                    CcPurchaseInfoSp pur = ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpById(info.getPurId());
                    if (!StringUtils.isNull(pur)) {
                        pur.setRkNum(pur.getRkNum().add(info.getRukuNum()));
                        pur.setRukuDate(info.getRukuDate());
                        ccPurchaseInfoSpMapper.updateCcPurchaseInfoSp(pur);
                    } else {
                        throw new ServiceException("采购订单不存在");
                    }
                }
            }

        }else {
            throw new ServiceException("物料不存在！");
        }
        return  1;
    }
    //订单扫码入库
    @Override
    @Transactional
    public int insertSmPurCcRukuInfo(CcRukuInfo ccRukuInfo) {
        JcWarehouseinfoKuwei kuwei = kuweiMapper.selectJcWarehouseinfoKuweiByKuweiJmCode(ccRukuInfo.getKuweiCode());
        CcPurchaseInfoSp spQuery=new CcPurchaseInfoSp();
        spQuery.setDanhao(ccRukuInfo.getPlanId());
        List<CcPurchaseInfoSp> purchaseInfoList = ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpSelectList(spQuery);
        if(purchaseInfoList.size()>0){
            String number= "RK-"+ NewNumber.createNewNumber(ccRukuInfoMapper.getNewCode(DateUtils.getDate()));
            for (CcPurchaseInfoSp info :purchaseInfoList) {
                CcRukuInfo rukuInfo=new CcRukuInfo();
                rukuInfo.setRukuType(ccRukuInfo.getRukuType());
                rukuInfo.setKuquCode(kuwei.getKuquCode());
                rukuInfo.setKuquName(kuwei.getKuquName());
                rukuInfo.setKuweiCode(kuwei.getKuweiCode());
                rukuInfo.setStockId(kuwei.getStockCode());
                rukuInfo.setStockName(kuwei.getStockName());
                rukuInfo.setDanhao(number);
                rukuInfo.setRukuDate(new Date());
                rukuInfo.setItemId(info.getItemId());
                rukuInfo.setItemCode(info.getItemCode());
                rukuInfo.setItemName(info.getItemName());
                rukuInfo.setClassId(info.getClassId());
                rukuInfo.setClassName(info.getClassName());
                rukuInfo.setSpec(info.getSpec());
                rukuInfo.setSupplyId(info.getSupplyId());
                rukuInfo.setSupplyName(info.getSupplyName());
                rukuInfo.setUnit(info.getUnit());
                rukuInfo.setRukuNum(info.getYhNum().subtract(info.getRkNum()));
                rukuInfo.setUnitPrice(info.getUnitPrice());
                rukuInfo.setTotalPrice(new BigDecimal("0"));
                rukuInfo.setLot(DateUtils.dateTime());
                rukuInfo.setIsTuoguan(info.getIsTuoguan());
                rukuInfo.setPurId(info.getId());
                rukuInfo.setContractCode(info.getContractCode());
                rukuInfo.setOrderDanhao(info.getDanhao());
                rukuInfo.setPlanId(info.getDanhao());
                rukuInfo.setOrderNum(info.getYddNum());
                rukuInfo.setPackingNum(info.getPackingNum());
                rukuInfo.setPlanNum(info.getYhNum());
                rukuInfo.setState(1L);
                ccRukuInfoMapper.insertCcRukuInfo(rukuInfo);
                this.saveStock(rukuInfo);
                info.setRkNum(info.getRkNum().add(rukuInfo.getRukuNum()));
                info.setRukuDate(info.getRukuDate());
                ccPurchaseInfoSpMapper.updateCcPurchaseInfoSp(info);
            }
        }else {
            throw new ServiceException("采购单号："+ccRukuInfo.getPlanId()+"不存在");
        }
        return 1;
    }
    /**
     * 修改入库单
     *
     * @param ccRukuInfo 入库单
     * @return 结果
     */
    @Override
    public int updateCcRukuInfo(CcRukuInfo ccRukuInfo)
    {
        String[] kuweiArr = ccRukuInfo.getWarehouse();
        if(kuweiArr.length==0){
            throw new ServiceException("仓库库位信息不能为空！");
        }
        JcWarehouseinfoKuwei kuwei = kuweiMapper.selectJcWarehouseinfoKuweiByKuweiJmCode(kuweiArr[2]);
        if(kuwei==null){
            throw new ServiceException("未找到库位信息！");
        }
        ccRukuInfo.setKuquCode(kuwei.getKuquCode());
        ccRukuInfo.setKuquName(kuwei.getKuquName());
        ccRukuInfo.setKuweiCode(kuwei.getKuweiJmCode());
        ccRukuInfo.setStockId(kuwei.getStockCode());
        ccRukuInfo.setStockName(kuwei.getStockName());
        ccRukuInfo.setUpdateTime(DateUtils.getNowDate());
        return ccRukuInfoMapper.updateCcRukuInfo(ccRukuInfo);
    }
    @Override
    @Transactional
    public String imporIteminfo(List<CcRukuInfo> rukuList, boolean updateSupport, String operName) {
        String number= "RK-"+ NewNumber.createNewNumber(ccRukuInfoMapper.getNewCode(DateUtils.getDate()));
        if (StringUtils.isNull(rukuList) || rukuList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CcRukuInfo ruku : rukuList)
        {
            try
            {
                if (StringUtils.isNotEmpty(ruku.getItemCode())&&StringUtils.isNotEmpty(ruku.getItemId())&& ruku.getRukuNum()!=null && ruku.getRukuNum().compareTo(new BigDecimal("0"))==1 && StringUtils.isNotEmpty(ruku.getItemName())&& StringUtils.isNotEmpty(ruku.getKuweiCode())){
                    BeanValidators.validateWithException(validator, ruku);
                    if(!StringUtils.isNotEmpty(ruku.getLot())){
                        ruku.setLot(DateUtils.dateTime());
                    }
                    if(StringUtils.isNull(ruku.getRukuDate())){
                        ruku.setRukuDate(new Date());
                    }
                    ruku.setRukuType(7L);
                    ruku.setQualityState("1");
                    ruku.setRukuDate(new Date());
                    JcWarehouseinfoKuwei kuwei = kuweiMapper.selectJcWarehouseinfoKuweiByKuweiJmCode(ruku.getKuweiCode());
                    if(kuwei==null){
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、库位编码 " + ruku.getKuweiCode() + "未找到库位信息";
                        failureMsg.append(msg);
                        continue;
                    }
                    //库位赋值
                    BeanUtils.copyProperties(kuwei,ruku);
                    ruku.setKuweiCode(kuwei.getKuweiJmCode());
                    ruku.setStockId(kuwei.getStockCode());
                    JcIteminfo item = jcIteminfoMapper.selectJcIteminfoByItemId(ruku.getItemId());
                    if(item==null){
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、物料子编号 " + ruku.getItemId() + "未找到物料信息";
                        failureMsg.append(msg);
                        continue;
                    }
                    //物料信息赋值
                    BeanUtils.copyProperties(item,ruku);
                    ruku.setId(null);
                    ruku.setCreateBy(operName);
                    ruku.setFactoryName(SecurityUtils.getFactoryName());
                    ruku.setFactoryCode(SecurityUtils.getFactoryCode());
                    ruku.setDanhao(number);
                    ruku.setCreateTime(DateUtils.getNowDate());
                    ruku.setCreateBy(SecurityUtils.getUsername());
                    ccRukuInfoMapper.insertCcRukuInfo(ruku);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、物料名称 " + ruku.getItemName() + " 导入成功");
                }else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、物料编号、物料子编号、物料名称、入库数量、仓库库位不能为空");
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、物料名称 " + ruku.getItemName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<CcRukuInfo> addRukuItemInfo(Long[] ids) {
        List<CcRukuInfo>  rukuDetailList =new ArrayList<>();
        List<JcIteminfo> jcIteminfoList = jcIteminfoMapper.selecIteminfoByIds(ids);
        if(jcIteminfoList.size()>0){
            for (JcIteminfo info :jcIteminfoList) {
                CcRukuInfo rukuInfo=new CcRukuInfo();
                rukuInfo.setItemId(info.getItemId());
                rukuInfo.setItemCode(info.getItemCode());
                rukuInfo.setItemName(info.getItemName());
                rukuInfo.setClassId(info.getClassId());
                rukuInfo.setClassName(info.getClassName());
                rukuInfo.setSpec(info.getSpec());
                rukuInfo.setSupplyId(info.getSupplyId());
                rukuInfo.setSupplyName(info.getSupplyName());
                rukuInfo.setUnit(info.getUnit());
                rukuInfo.setRukuNum(new BigDecimal("0"));
                rukuInfo.setUnitPrice(new BigDecimal("0"));
                rukuInfo.setTotalPrice(new BigDecimal("0"));
                rukuInfo.setLot(DateUtils.dateTime());
                rukuInfo.setIsTuoguan(info.getIsTuoguan());
                CcStockInfo ccStockInfo=new CcStockInfo();
                ccStockInfo.setItemId(info.getItemCode());
                //默认库位
                CcStockInfo stockInfo = stockInfoMapper.selectCcStockInfoDefault(ccStockInfo);
                if(stockInfo!=null){
                    String [] str=new String[3];
                    str[0]=stockInfo.getStockId();
                    str[1]=stockInfo.getKuquCode();
                    str[2]=stockInfo.getKuweiCode();
                    rukuInfo.setWarehouse(str);
                }
                rukuDetailList.add(rukuInfo);
            }
        }
        return rukuDetailList;
    }
    //添加采购的物料
    @Override
    public List<CcRukuInfo> addPurRukuItemInfo(Long[] ids) {
        List<CcRukuInfo>  rukuDetailList =new ArrayList<>();
        List<CcPurchaseInfoSp> purchaseInfoList = ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpListByIds(ids);
        if(purchaseInfoList.size()>0){
            for (CcPurchaseInfoSp info :purchaseInfoList) {
                CcRukuInfo rukuInfo=new CcRukuInfo();
                rukuInfo.setItemId(info.getItemId());
                rukuInfo.setItemCode(info.getItemCode());
                rukuInfo.setItemName(info.getItemName());
                rukuInfo.setClassId(info.getClassId());
                rukuInfo.setClassName(info.getClassName());
                rukuInfo.setSpec(info.getSpec());
                rukuInfo.setSupplyId(info.getSupplyId());
                rukuInfo.setSupplyName(info.getSupplyName());
                rukuInfo.setUnit(info.getUnit());
                rukuInfo.setRukuNum(info.getYhNum().subtract(info.getRkNum()));
                rukuInfo.setUnitPrice(info.getUnitPrice());
                rukuInfo.setTotalPrice(new BigDecimal("0"));
                rukuInfo.setLot(DateUtils.dateTime());
                rukuInfo.setIsTuoguan(info.getIsTuoguan());
                rukuInfo.setPurId(info.getId());
                rukuInfo.setContractCode(info.getContractCode());
                rukuInfo.setOrderDanhao(info.getDanhao());
                rukuInfo.setPlanId(info.getDanhao());
                rukuInfo.setOrderNum(info.getYddNum());
                rukuInfo.setPackingNum(info.getPackingNum());
                rukuInfo.setPlanNum(info.getYhNum().subtract(info.getRkNum()));
                JcWarehouseinfoKuwei kuwei=new JcWarehouseinfoKuwei();
                kuwei.setTenantId(SecurityUtils.getFactoryCode());
                kuwei.setDeptId(SecurityUtils.getDeptId().toString());
                kuwei.setKuweiType("3");
                //默认库位
                 kuwei = kuweiMapper.selectJcWarehouseinfoKuweiRkDefault(kuwei);
                 if(kuwei != null){
                    String [] str=new String[3];
                    str[0]=kuwei.getStockCode();
                    str[1]=kuwei.getKuquCode();
                    str[2]=kuwei.getKuweiJmCode();
                    rukuInfo.setWarehouse(str);
                }
                rukuDetailList.add(rukuInfo);
            }
        }
        return rukuDetailList;
    }
    //添加出库流转物料
    @Override
    public List<CcRukuInfo> addChukuRukuItemInfo(Long[] ids) {
        List<CcRukuInfo>  rukuDetailList =new ArrayList<>();
        List<CcChukuInfo> ccChukuInfoList = chukuInfoMapper.selectCcChukuInfoByIds(ids);
        if(ccChukuInfoList.size()>0){
            for (CcChukuInfo info :ccChukuInfoList) {
                CcRukuInfo rukuInfo=new CcRukuInfo();
                rukuInfo.setItemId(info.getItemId());
                rukuInfo.setItemCode(info.getItemCode());
                rukuInfo.setItemName(info.getItemName());
                rukuInfo.setClassId(info.getClassId());
                rukuInfo.setClassName(info.getClassName());
                rukuInfo.setSpec(info.getSpec());
                rukuInfo.setSupplyId(info.getSupplyId());
                rukuInfo.setSupplyName(info.getSupplyName());
                rukuInfo.setUnit(info.getUnit());
                rukuInfo.setRukuNum(info.getCkNum().subtract(info.getZzrkNum()));
                rukuInfo.setUnitPrice(info.getUnitPrice());
                rukuInfo.setTotalPrice(info.getTotalPrice());
                rukuInfo.setLot(DateUtils.dateTime());
                rukuInfo.setIsTuoguan(info.getIsTuoguan());
                rukuInfo.setCkId(info.getId());
                rukuInfo.setContractCode(info.getContractCode());
                rukuInfo.setOrderDanhao(info.getOrderDanhao());
                rukuInfo.setPlanId(info.getDanhao());
                rukuInfo.setStockId(info.getReceivingStockId());
                //rukuInfo.setOrderNum(info.ge());
                //rukuInfo.setPackingNum(info.getp());
                rukuInfo.setPlanNum(info.getCkNum());
             /*   CcStockinfoInfo ccStockinfoInfo=new CcStockinfoInfo();
                ccStockinfoInfo.setItemId(info.getItemCode());*/
              /*  //默认库位
                List<CcStockinfoInfo> stockinfoInfos = selectListinfo.selectListinfo(ccStockinfoInfo);
                if(stockinfoInfos.size()>0){
                    ccStockinfoInfo=stockinfoInfos.get(0);
                    rukuInfo.setKuquCode(ccStockinfoInfo.getKuquCode());
                    rukuInfo.setKuquName(ccStockinfoInfo.getKuquName());
                    rukuInfo.setKuweiCode(ccStockinfoInfo.getKuweiCode());
                }*/
                //默认库位
//                JcWarehouseinfoKuwei kuwei=new JcWarehouseinfoKuwei();
//                kuwei.setTenantId(SecurityUtils.getFactoryCode());
//                kuwei.setDeptId(SecurityUtils.getDeptId().toString());
//                kuwei.setKuweiType("2");
//                kuwei = kuweiMapper.selectJcWarehouseinfoKuweiRkDefault(kuwei);
//                if(kuwei != null){
//                    String [] str=new String[3];
//                    str[0]=kuwei.getStockCode();
//                    str[1]=kuwei.getKuquCode();
//                    str[2]=kuwei.getKuweiJmCode();
//                    rukuInfo.setWarehouse(str);
//                }
                String [] str=new String[3];
                str[0]="ZQEY0001";
                str[1]="ZQEY0001.001";
                str[2]="ZQEY0001.001.00001";
                rukuInfo.setWarehouse(str);
                rukuDetailList.add(rukuInfo);
            }
        }
        return rukuDetailList;
    }

    @Override
    @Transactional
    public int zhixingRuku(Long[] ids) {
        for (int i = 0; i <ids.length ; i++) {
            CcRukuInfo rukuInfo=  ccRukuInfoMapper.selectCcRukuInfoById(ids[i]);
            if("1".equals(rukuInfo.getJiesuanState())){
                throw new ServiceException("入库单物料【"+rukuInfo.getItemId()+"】已结算，不允许执行操作！！！");
            }
            if(1L==rukuInfo.getState().longValue()){
                throw new ServiceException("入库单物料【"+rukuInfo.getItemId()+"】已执行，请勿重复执行操作！！！");
            }
            //查询库存的物料
            CcStockInfo stockInfo = stockInfoMapper.selectCcStockinfoInfoByItemIdAndSuppIdAndUnitPrice(rukuInfo.getItemId(), rukuInfo.getSupplyId(),rukuInfo.getUnitPrice());
            //如果是null新增物料库存 否则修改新增库存
            if(stockInfo==null){
                stockInfo =new CcStockInfo();
                stockInfo.setDeptId(SecurityUtils.getDeptId());
                stockInfo.setItemId(rukuInfo.getItemId());
                stockInfo.setItemCode(rukuInfo.getItemCode());
                stockInfo.setItemName(rukuInfo.getItemName());
                stockInfo.setSpec(rukuInfo.getSpec());
                stockInfo.setUnit(rukuInfo.getUnit());
                stockInfo.setKcNum(rukuInfo.getRukuNum());
                stockInfo.setKyNum(rukuInfo.getRukuNum());
                stockInfo.setSupplyId(rukuInfo.getSupplyId());
                stockInfo.setSupplyName(rukuInfo.getSupplyName());
                stockInfo.setMakerCode(rukuInfo.getMakerCode());
                stockInfo.setMakerName(rukuInfo.getMakerName());
                stockInfo.setClassId(rukuInfo.getClassId());
                stockInfo.setClassName(rukuInfo.getClassName());
                stockInfo.setStockId(rukuInfo.getStockId());
                stockInfo.setStockName(rukuInfo.getStockName());
                stockInfo.setKuquCode(rukuInfo.getKuquCode());
                stockInfo.setKuquName(rukuInfo.getKuquName());
                stockInfo.setKuweiCode(rukuInfo.getKuweiCode());
                stockInfo.setCreateBy(SecurityUtils.getUsername());
                stockInfo.setCreateTime(new Date());
                stockInfo.setLot(rukuInfo.getLot());
                stockInfo.setUnitPrice(rukuInfo.getUnitPrice());
                stockInfo.setUnitPrice(rukuInfo.getUnitPrice());
                stockInfo.setTotalPrice(rukuInfo.getTotalPrice());
                stockInfo.setRukuId(rukuInfo.getDanhao());
                stockInfo.setContractCode(rukuInfo.getContractCode());
                stockInfo.setFactoryCode(rukuInfo.getFactoryCode());
                stockInfo.setFactoryName(rukuInfo.getFactoryName());
                stockInfo.setIsTuoguan(rukuInfo.getIsTuoguan());
                stockInfo.setTxm(rukuInfo.getTxm());
                stockInfo.setRukuDate(rukuInfo.getRukuDate());
                stockInfo.setPackingNum(rukuInfo.getPackingNum());
                stockInfo.setSaleOrderCode(rukuInfo.getOrderDanhao());
                stockInfo.setClientName(rukuInfo.getClientName());
                stockInfo.setClientCode(rukuInfo.getClientCode());
                stockInfoMapper.insertCcStockInfo(stockInfo);
            }else {
                stockInfo.setUpdateBy(SecurityUtils.getUsername());
                stockInfo.setUpdateTime(new Date());
                stockInfo.setKcNum(stockInfo.getKcNum().add(rukuInfo.getRukuNum()));
                stockInfo.setKyNum(stockInfo.getKyNum().add(rukuInfo.getRukuNum()));
                stockInfo.setRukuDate(rukuInfo.getRukuDate());
                stockInfo.setTotalPrice(stockInfo.getUnitPrice().multiply(stockInfo.getKcNum()));
                stockInfoMapper.updateCcStockInfo(stockInfo);
            }
            rukuInfo.setState(1L);
            ccRukuInfoMapper.updateCcRukuInfo(rukuInfo);
        }
        return 1;
    }
    public void saveStock(CcRukuInfo rukuInfo){
        //下面不执行直接入库，同步库存
        //查询库存的物料
        //相同供应商，库位，价格的合并
        CcStockInfo stockInfo = stockInfoMapper.selectCcStockinfoInfoByItemIdAndSuppIdAndUnitPrice(rukuInfo.getItemId(), rukuInfo.getSupplyId(),rukuInfo.getUnitPrice());
        //如果是null新增物料库存 否则修改合并新增库存
        if(stockInfo==null){
            stockInfo =new CcStockInfo();
            stockInfo.setDeptId(SecurityUtils.getDeptId());
            stockInfo.setItemId(rukuInfo.getItemId());
            stockInfo.setItemCode(rukuInfo.getItemCode());
            stockInfo.setItemName(rukuInfo.getItemName());
            stockInfo.setSpec(rukuInfo.getSpec());
            stockInfo.setUnit(rukuInfo.getUnit());
            stockInfo.setKcNum(rukuInfo.getRukuNum());
            stockInfo.setKyNum(rukuInfo.getRukuNum());
            stockInfo.setSupplyId(rukuInfo.getSupplyId());
            stockInfo.setSupplyName(rukuInfo.getSupplyName());
            stockInfo.setMakerCode(rukuInfo.getMakerCode());
            stockInfo.setMakerName(rukuInfo.getMakerName());
            stockInfo.setClassId(rukuInfo.getClassId());
            stockInfo.setClassName(rukuInfo.getClassName());
            stockInfo.setStockId(rukuInfo.getStockId());
            stockInfo.setStockName(rukuInfo.getStockName());
            stockInfo.setKuquCode(rukuInfo.getKuquCode());
            stockInfo.setKuquName(rukuInfo.getKuquName());
            stockInfo.setKuweiCode(rukuInfo.getKuweiCode());
            stockInfo.setCreateBy(SecurityUtils.getUsername());
            stockInfo.setCreateTime(new Date());
            stockInfo.setLot(rukuInfo.getLot());
            stockInfo.setUnitPrice(rukuInfo.getUnitPrice());
            stockInfo.setTotalPrice(stockInfo.getUnitPrice().multiply(stockInfo.getKyNum()));
            stockInfo.setRukuId(rukuInfo.getDanhao());
            stockInfo.setContractCode(rukuInfo.getContractCode());
            stockInfo.setFactoryCode(rukuInfo.getFactoryCode());
            stockInfo.setFactoryName(rukuInfo.getFactoryName());
            stockInfo.setIsTuoguan(rukuInfo.getIsTuoguan());
            stockInfo.setTxm(rukuInfo.getTxm());
            stockInfo.setRukuDate(rukuInfo.getRukuDate());
            stockInfo.setPackingNum(rukuInfo.getPackingNum());
            stockInfo.setSaleOrderCode(rukuInfo.getOrderDanhao());
            stockInfo.setClientName(rukuInfo.getClientName());
            stockInfo.setClientCode(rukuInfo.getClientCode());
            stockInfoMapper.insertCcStockInfo(stockInfo);
        }else {
            stockInfo.setSupplyId(rukuInfo.getSupplyId());
            stockInfo.setSupplyName(rukuInfo.getSupplyName());
            stockInfo.setUpdateBy(SecurityUtils.getUsername());
            stockInfo.setUpdateTime(new Date());
            stockInfo.setKcNum(stockInfo.getKcNum().add(rukuInfo.getRukuNum()));
            stockInfo.setKyNum(stockInfo.getKyNum().add(rukuInfo.getRukuNum()));
            stockInfo.setRukuDate(rukuInfo.getRukuDate());
            stockInfo.setUnitPrice(rukuInfo.getUnitPrice());
            stockInfo.setTotalPrice(stockInfo.getUnitPrice().multiply(stockInfo.getKyNum()));
            stockInfoMapper.updateCcStockInfo(stockInfo);
        }
    }

    /**
     * 批量删除入库单
     *
     * @param ids 需要删除的入库单主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCcRukuInfoByIds(Long[] ids)
    {
        for (int i = 0; i <ids.length ; i++) {
            CcRukuInfo rukuinfo = ccRukuInfoMapper.selectCcRukuInfoById(ids[i]);
            if("1".equals(rukuinfo.getJiesuanState())){
                throw new ServiceException("入库单物料【"+rukuinfo.getItemId()+"】已结算，不允许执行操作！！！");
            }
            if(rukuinfo.getState().longValue()==0L){
                throw new ServiceException("入库单未执行无需撤销！！！");
            }
            if(rukuinfo.getState().longValue()==2L){
                throw new ServiceException("入库单已撤销无需重复撤销！！！");
            }
            CcStockInfo stockInfo = stockInfoMapper.selectCcStockinfoInfoByItemIdAndSuppIdAndUnitPrice(rukuinfo.getItemId(), rukuinfo.getSupplyId(),rukuinfo.getUnitPrice());
            if(stockInfo!=null){
                if(stockInfo.getKyNum().compareTo(rukuinfo.getRukuNum())<0){
                    throw new ServiceException("库存不足撤销失败！！！");
                }
                stockInfo.setKcNum(stockInfo.getKcNum().subtract(rukuinfo.getRukuNum()));
                stockInfo.setKyNum(stockInfo.getKcNum().subtract(stockInfo.getLockNum()));
                stockInfo.setTotalPrice(stockInfo.getUnitPrice().multiply(stockInfo.getKcNum()));
                stockInfoMapper.updateCcStockInfo(stockInfo);
                rukuinfo.setState(2L);
                ccRukuInfoMapper.updateCcRukuInfo(rukuinfo);
            }else {
                throw new ServiceException("未找到入库库存！！！");
            }
            if(rukuinfo.getRukuType().longValue()==0L){
                CcPurchaseInfoSp pur = ccPurchaseInfoSpMapper.selectCcPurchaseInfoSpById(rukuinfo.getPurId());
                if(!StringUtils.isNull(pur)){
                    pur.setRkNum(pur.getRkNum().subtract(rukuinfo.getRukuNum()));
                    pur.setRukuDate(rukuinfo.getRukuDate());
                    ccPurchaseInfoSpMapper.updateCcPurchaseInfoSp(pur);
                }else{
                    throw new ServiceException("采购订单不存在");
                }
            }
            if(rukuinfo.getState().longValue()==0L){
                return ccRukuInfoMapper.deleteCcRukuInfoById(rukuinfo.getId());
            }
        }
        return 1;
    }

    @Override
    public int deleteCcRukuInfoByIds2(Long[] ids) {
        for (int i = 0; i <ids.length ; i++) {
            CcRukuInfo rukuinfo = ccRukuInfoMapper.selectCcRukuInfoById(ids[i]);
            if ("1".equals(rukuinfo.getJiesuanState())) {
                throw new ServiceException("入库单物料【" + rukuinfo.getItemId() + "】已结算，不允许执行操作！！！");
            }
            if (rukuinfo.getState().longValue() == 1L) {
                throw new ServiceException("入库单已执行，不允许删除操作！！！");
            }
        }
        return ccRukuInfoMapper.deleteCcRukuInfoByIds(ids);
    }

    /**
     * 删除入库单信息
     *
     * @param id 入库单主键
     * @return 结果
     */
    @Override
    public int deleteCcRukuInfoById(Long id)
    {
        return ccRukuInfoMapper.deleteCcRukuInfoById(id);
    }


}
